package com.zj.sms.http;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.zj.sms.constant.Constants;

public class HttpClient {
	private static Logger logger = Logger.getLogger(HttpClient.class);
	CloseableHttpClient client = HttpClients.createDefault();
	//设置请求超时时间 https://my.oschina.net/wallechen/blog/526642
	RequestConfig requestConfig = RequestConfig.custom().setCircularRedirectsAllowed(false)//允许重定向
			.setConnectTimeout(6000)//设置连接超时时间，单位毫秒
			.setConnectionRequestTimeout(12000)
			.setSocketTimeout(15000).build();//请求获取数据的超时时间，单位毫秒
	
	private HttpClient(){}
	private static HttpClient httpClient;
	public static HttpClient getInstance(){
		if(httpClient == null)
			httpClient = new HttpClient();
		return httpClient;
	}
	/**
	 * 获取get请求上的网页数据
	 * 为了线程安全，直接在方法里声明变量，不然多个线程对同一个对象的类成员变量赋值取值时会出现值不一致问题
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public String getContent(HttpGet get) throws ClientProtocolException, IOException{
		String content = null;
		get.setConfig(requestConfig);
		CloseableHttpResponse response = client.execute(get);
		
		//非常重要,判断url是否是网页，不是的话就不加进去了
		Header contentType = response.getFirstHeader("Content-Type");
		if(contentType == null || !contentType.getValue().contains("text") || !contentType.getValue().contains("html")){
			logger.info(get.getURI()+"非网页，跳过!"+contentType == null?"":contentType.getValue());
			return null;
		}
		content = EntityUtils.toString(response.getEntity(),Constants.charSet).trim();
		response.close();
		get.releaseConnection();
		return content;
	}
}
